package com.example.stray_animal_management_system.controller;

import com.example.stray_animal_management_system.entity.User;
import com.example.stray_animal_management_system.service.UserService;
import com.example.stray_animal_management_system.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 用户登录和注册
 * @author: panpan
 * @time: 2025/10/26
 */
@RestController
@RequestMapping("/api/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginInterceptor loginInterceptor;

    // 注册
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> res = new HashMap<>();
        try {
            userService.register(user);
            res.put("code", 200);
            res.put("msg", "注册成功");
            res.put("userId", user.getId()); // 新注册用户ID
            res.put("username", user.getUsername());
            res.put("email", user.getEmail());
            res.put("phone", user.getPhone());
            res.put("roleId", user.getRoleId());
            res.put("status", user.getStatus()); // 用户状态，1=正常
            res.put("T", System.currentTimeMillis()); // 返回当前时间戳
        } catch (Exception e) {
            res.put("code", 400);
            res.put("msg", e.getMessage());
        }
        return res;
    }

    // 登录
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user, HttpServletRequest request) {
        Map<String, Object> res = new HashMap<>();
        try {
            User dbUser = userService.login(user.getUsername(), user.getPassword());

            // 登录成功，设置返回信息
            res.put("code", 200);
            res.put("msg", "登录成功");
            res.put("userId", dbUser.getId());
            res.put("username", dbUser.getUsername());
            res.put("roleId", dbUser.getRoleId());
            res.put("email", dbUser.getEmail());
            res.put("phone", dbUser.getPhone());
            res.put("status", dbUser.getStatus());
            res.put("nickname", dbUser.getNickname() != null ? dbUser.getNickname() : "暂无昵称");
            res.put("T", System.currentTimeMillis()); // 当前时间戳

            // 登录成功后记录登录信息（IP、设备、浏览器、操作系统等）
            try {
                loginInterceptor.recordLoginInfo(request, dbUser.getId(), dbUser.getUsername());
            } catch (Exception e) {
                // 记录登录信息失败不影响登录流程，只记录日志
                System.err.println("记录登录信息失败：" + e.getMessage());
                e.printStackTrace();
            }

        } catch (Exception e) {
            res.put("code", 400);
            res.put("msg", e.getMessage());
        }
        return res;
    }

}